﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SerialCommon sc = new SerialCommon();
        private void button1_Click(object sender, EventArgs e)
        {
            string str = textBox1.Text;
            byte[] sedData = System.Text.Encoding.Default.GetBytes(str);
                sc.SendData(sedData);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
            comboBox1.Items.AddRange(sc.portName);

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            sc.InitComm(comboBox1.Text, 9600, 8, System.IO.Ports.StopBits.One, System.IO.Ports.Parity.None);
            if (!sc.OpenPort())
            {
                MessageBox.Show("串口打开失败");
                
            }
            sc.MySerialPort.DataReceived += new SerialDataReceivedEventHandler(ReceivedData);
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            byte[] rs=sc.ReceiveData(1000);
            string str = System.Text.Encoding.UTF8.GetString(rs);
            textBox2.AppendText("接收： " + str);
        }
        //数据接收方法
        public void ReceivedData(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] data = sc.ReceiveData(1000);
            string str = System.Text.Encoding.UTF8.GetString(data);
            this.BeginInvoke(new Action(() =>
            {
                textBox2.AppendText("接收： " + str);
            }));
            //对接收的数据进行处理
            //注意这是异步的，跟主窗体不是同一个线程
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
